package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.graphics.Bitmap;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.SeekBar;

import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import VideoHandle.EpDraw;
import VideoHandle.EpEditor;
import VideoHandle.EpVideo;
import VideoHandle.OnEditorListener;
import flc.ast.BaseAc;
import flc.ast.HomeActivity;
import flc.ast.R;
import flc.ast.adapter.ColorAdapter;
import flc.ast.bean.ColorBean;
import flc.ast.databinding.ActivityViewTextBinding;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.utils.FileP2pUtil;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.MediaUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.TimeUtil;
import stark.common.basic.view.container.StkRelativeLayout;

public class ViewTextActivity extends BaseAc<ActivityViewTextBinding> {

    public static String videoPath;
    private int oldPosition=0;
    private List<ColorBean> listColor = new ArrayList<>();
    private ColorAdapter colorAdapter;
    private int videoWidth,videoHeight;
    private long videoLength;
    private Handler mHandler;
    private final Runnable mTaskUpdateTime = new Runnable() {
        @Override
        public void run() {
            mDataBinding.tvVideoSbLeft.setText(TimeUtil.getMmss(mDataBinding.videoView.getCurrentPosition()));
            mDataBinding.sbVideo.setProgress(Integer.parseInt(TimeUtils.millis2String(mDataBinding.videoView.getCurrentPosition(), "ss")));
            mHandler.postDelayed(this, 500);
        }
    };

    @Override
    protected int onCreate() {
        return R.layout.activity_view_text;
    }

    @Override
    protected void initView() {
        mDataBinding.ivVideoTextBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mDataBinding.ivVideoPlay.setOnClickListener(this);
        mDataBinding.ivVideoTextComp.setOnClickListener(this);
        mDataBinding.ivGenerate.setOnClickListener(this);
        mDataBinding.tvDeriveVideo.setOnClickListener(this);
        mDataBinding.rvTextColorList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        colorAdapter = new ColorAdapter();
        mDataBinding.rvTextColorList.setAdapter(colorAdapter);
        colorAdapter.setOnItemClickListener(this);
    }


    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivVideoPlay:
                if (mDataBinding.videoView.isPlaying()) {
                    mDataBinding.ivVideoPlay.setImageResource(R.drawable.bofang1);
                    mDataBinding.videoView.pause();
                    stopTime();
                } else {
                    mDataBinding.ivVideoPlay.setImageResource(R.drawable.zanting1);
                    mDataBinding.videoView.start();
                    startTime();
                }
                break;
            case R.id.ivVideoTextComp:
                if (mDataBinding.etVideoText.getText().toString().isEmpty()){
                    ToastUtils.showShort(getString(R.string.please_input_text2));
                    return;
                }
                mDataBinding.tvStickerViewText.setText(mDataBinding.etVideoText.getText().toString());
                mDataBinding.etVideoText.setText("");
                break;
            case R.id.ivGenerate:
                videoText();
                break;
            case R.id.tvDeriveVideo:
                saveVideo();
                break;

        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        colorAdapter.getItem(oldPosition).setSelect(false);
        colorAdapter.notifyItemChanged(oldPosition);
        oldPosition=position;
        colorAdapter.getItem(position).setSelect(true);
        colorAdapter.notifyItemChanged(position);
        mDataBinding.tvStickerViewText.setTextColor(Color.parseColor(colorAdapter.getItem(position).getColor()));
    }

    @Override
    protected void initData() {
        //获取视频路径 时长
        if (TextUtils.isEmpty(videoPath)) return;
        videoLength = MediaUtil.getDuration(videoPath);
        //设置播放器
        setPlayer();
        setSticker();
        listColor.add(new ColorBean("#000000", true));
        listColor.add(new ColorBean("#FFFFFF", false));
        listColor.add(new ColorBean("#D8D8D8", false));
        listColor.add(new ColorBean("#FF8F8F", false));
        listColor.add(new ColorBean("#FFBE46", false));
        listColor.add(new ColorBean("#FFEB47", false));
        listColor.add(new ColorBean("#9BDC3D", false));
        listColor.add(new ColorBean("#45C965", false));
        listColor.add(new ColorBean("#4FADB6", false));
        listColor.add(new ColorBean("#3C49DD", false));
        listColor.add(new ColorBean("#6140AA", false));
        listColor.add(new ColorBean("#C050DE", false));
        listColor.add(new ColorBean("#E74F8E", false));
        listColor.add(new ColorBean("#C82222", false));
        Log.e("TAG", "initData: "+listColor.size() );
        colorAdapter.setList(listColor);
        mDataBinding.tvStickerViewText.setTextColor(Color.parseColor("#000000"));
    }

    private void videoText(){
        RxUtil.create(new RxUtil.Callback<Boolean>() {
            private String imagePath;

            @Override
            public void doBackground(ObservableEmitter<Boolean> emitter) {
                Bitmap bitmap = ImageUtils.view2Bitmap(mDataBinding.tvStickerViewText);
                imagePath = FileUtil.generateFilePath(Content.myTemp, getString(R.string.unit_png));
                boolean save = ImageUtils.save(bitmap, imagePath, Bitmap.CompressFormat.PNG);
                emitter.onNext(save);
            }

            @Override
            public void accept(Boolean isSave) {
                if (isSave) {
                    EpDraw epDraw = new EpDraw(imagePath, 0, 0, videoWidth, videoHeight, false);
                    epDraw.setRotate(0);
                    String resultFile = FileUtil.generateFilePath(Content.myTemp, getString(R.string.unit_mp4));
                    EpVideo epVideo = new EpVideo(videoPath);
                    epVideo.addDraw(epDraw);
                    EpEditor.OutputOption outputOption = new EpEditor.OutputOption(resultFile);
                    EpEditor.exec(epVideo, outputOption, new OnEditorListener() {
                        @Override
                        public void onSuccess() {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    dismissDialog();
                                    mDataBinding.tvStickerViewText.clearTextContent();
                                    videoPath=resultFile;
                                    mDataBinding.tvDeriveVideo.setEnabled(true);
                                    mDataBinding.videoView.setVideoPath(videoPath);
                                    mDataBinding.videoView.seekTo(1);
                                    mDataBinding.ivVideoPlay.setImageResource(R.drawable.zanting1);
                                    mDataBinding.videoView.start();
                                }
                            });
                        }

                        @Override
                        public void onFailure() {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    dismissDialog();
                                    mDataBinding.tvDeriveVideo.setEnabled(true);
                                    ToastUtils.showShort(R.string.save_def);
                                }
                            });
                        }

                        @Override
                        public void onProgress(float progress) {
                            if (progress < 0) {
                                progress = 0;
                            } else if (progress > 1) {
                                progress = 1;
                            }
                            showDialog(getString(R.string.text_ing)
                                    + new DecimalFormat(getString(R.string.unit_num1)).format(progress * 100)
                                    + getString(R.string.unit_percent));
                        }
                    });
                }
            }
        });
    }

    //临时保存视频
    private void saveVideo() {
        showDialog(getString(R.string.save_video_ing));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                RxUtil.create(new RxUtil.Callback<String>() {
                    @Override
                    public void doBackground(ObservableEmitter<String> emitter) {
                        //保存到相册
                        FileP2pUtil.copyPrivateVideoToPublic(mContext, videoPath);
                        emitter.onNext("");
                    }

                    @Override
                    public void accept(String path) {
                        dismissDialog();
                        ToastUtils.showShort(R.string.save_suc);
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                startActivity(HomeActivity.class);
                            }
                        },500);
                    }
                });
            }
        }, 1000);
    }

    //设置播放器
    private void setPlayer() {
        mHandler = new Handler();
        //设置seekbar
        mDataBinding.sbVideo.setMax(Integer.parseInt(TimeUtils.millis2String(videoLength, "ss")));
        mDataBinding.tvVideoSbLeft.setText("00:00");
        mDataBinding.tvVideoSbRight.setText(TimeUtil.getMmss(videoLength));
        mDataBinding.sbVideo.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                mDataBinding.videoView.seekTo(seekBar.getProgress());
            }
        });
        //设置播放器
        mDataBinding.videoView.setVideoPath(videoPath);
        mDataBinding.videoView.seekTo(1);
        mDataBinding.videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {  // 播放完成的监听
                mDataBinding.tvVideoSbLeft.setText("00:00");
                mDataBinding.sbVideo.setProgress(0);
                mDataBinding.ivVideoPlay.setImageResource(R.drawable.bofang1);
                mp.seekTo(1);
                stopTime();
            }
        });
    }

    private void startTime() {
        mHandler.post(mTaskUpdateTime);
    }

    private void stopTime() {
        mHandler.removeCallbacks(mTaskUpdateTime);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //直接播放视频
        mDataBinding.videoView.seekTo(1);
        mDataBinding.ivVideoPlay.setImageResource(R.drawable.zanting1);
        mDataBinding.videoView.start();
        startTime();
    }

    @Override
    protected void onStop() {
        super.onStop();
        stopTime();
    }

    //设置贴纸
    private void setSticker() {
        // 获取videoView真实的宽高大小
        mDataBinding.videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                videoWidth = mp.getVideoWidth();
                videoHeight = mp.getVideoHeight();
            }
        });
        // 将stickerView的宽高大小设置成videoView一样的大小
        mDataBinding.videoView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                StkRelativeLayout.LayoutParams stickerLayoutParams = (StkRelativeLayout.LayoutParams) mDataBinding.tvStickerViewText.getLayoutParams();
                stickerLayoutParams.width = right - left;
                stickerLayoutParams.height = bottom - top;
                mDataBinding.tvStickerViewText.setLayoutParams(stickerLayoutParams);
            }
        });
    }

}